package com.ctgu.tengyun.filter;

import com.ctgu.tengyun.bean.TokenBean;
import com.ctgu.tengyun.bean.response.BaseResponse;
import com.ctgu.tengyun.bean.response.RespGenerator;
import com.ctgu.tengyun.exception.UnAuthorizedException;
import com.ctgu.tengyun.util.JsonUtil;
import com.ctgu.tengyun.util.RequestExtract;
import com.ctgu.tengyun.util.ServletUtil;
import com.ctgu.tengyun.util.TokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


public class UserAuthorizationFilter implements Filter {

    public static final Logger logger = LoggerFactory.getLogger(UserAuthorizationFilter.class);

    private String[] excludedUris;

    public void init(FilterConfig config) throws ServletException {
        logger.info("init UserAuthorizationFilter");
        excludedUris = config.getInitParameter("exclusions").split(",");
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpServletRequest requestWrpper = (HttpServletRequest) request;

        String url = requestWrpper.getRequestURI();
        if (isExcludedUri(url)) {
            try {
                chain.doFilter(requestWrpper, response);
                return;
            } catch (Exception e) {
                logger.warn("exclude url:" + url + ", chain dofilter error.", e);
            }
        }

        try {
            if ("options".equalsIgnoreCase(requestWrpper.getMethod())) {
                chain.doFilter(requestWrpper, response);
                return;
            }

            //获取请求token
            String token = RequestExtract.getToken(requestWrpper);
            TokenBean tokenBean = TokenUtil.validatePassportToken(token);
            if (tokenBean != null) {
                RequestExtract.setRequestUser(requestWrpper, tokenBean);
                chain.doFilter(requestWrpper, response);
            }else{
                logger.info("auth filter. auth failed. {}, url:{}", ServletUtil.getRemoteAddress(requestWrpper), requestWrpper.getRequestURI());
                throw new UnAuthorizedException("auth filter. auth failed");
            }
        } catch (Exception e) {
            httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            logger.info("auth filter. auth failed. {}, url:{}", ServletUtil.getRemoteAddress(requestWrpper), requestWrpper.getRequestURI(), e);
            PrintWriter out = null;
            try {
                out = response.getWriter();
                BaseResponse baseResponse = RespGenerator.getUnauthErrResp("auth token error");
                out.append(JsonUtil.format(baseResponse));
            } catch (IOException ignore) {

            } finally {
                if (out != null) {
                    out.close();
                }
            }
        }

    }

    private boolean isExcludedUri(String uri) {
        if (excludedUris == null || excludedUris.length <= 0) {
            return false;
        }
        for (String ex : excludedUris) {
            if (uri.contains(ex)) {
                return true;
            }
        }
        return false;
    }

    public void destroy() {}
}